package com.cszy.ewmxns.common

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.cysd.ewmxns.sdw_ui.activity.HotSplashActivity
import com.cysd.ewmxns.sdw_ui.activity.SingleHotSplashActivity
import com.cysd.ewmxns.sdw_ui.activity.SplashActivity
import com.cysd.ewmxns.sdw_utils.SpUtils
import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans


object  AppLifecycleTracker:LifecycleObserver {
    private var wasInBackground = true // 默认 true，确保首次启动不误触发
    private var lastBackgroundTime = 0L // 记录上次退到后台的时间戳
    private val MIN_BACKGROUND_TIME = 1000L // 最小后台停留时间（1秒）
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onAppForegrounded() {
        // 如果从退到后台到返回前台的时间 < 2秒，则不触发

        if (lastBackgroundTime > 0 &&
            System.currentTimeMillis() - lastBackgroundTime >= MIN_BACKGROUND_TIME) {
            launchTargetActivity()
        }
        lastBackgroundTime = 0 // 重置时间戳
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onAppBackgrounded() {
        lastBackgroundTime = System.currentTimeMillis() // 记录退到后台的时间
        wasInBackground = true
    }

    private fun launchTargetActivity() {
         if (isBlacklistMode())return
        // 检查当前栈顶 Activity 是否是 SplashActivity
        if (isActivityOnTop(BaseApplication.application, SplashActivity::class.java)) {
            return // 如果是 SplashActivity，则不触发 TargetActivity
        }
        // 获取当前 Top Activity 的 Context
        val context = BaseApplication.application
        // 避免重复启动（例如目标 Activity 已经是栈顶）
        if (isTargetActivityOnTop(context)) return

        val intent = Intent(context, HotSplashActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK // 确保从后台启动
        }
        context.startActivity(intent)
    }

    /** 检查目标 Activity 是否已在栈顶 */
    private fun isTargetActivityOnTop(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTasks = activityManager.getRunningTasks(1)
        return runningTasks.firstOrNull()?.topActivity?.className == SingleHotSplashActivity::class.java.name
    }

    /** 检查指定 Activity 是否在栈顶 */
    private fun isActivityOnTop(context: Context, activityClass: Class<*>): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTasks = activityManager.getRunningTasks(1)
        return runningTasks.firstOrNull()?.topActivity?.className == activityClass.name
    }
    // 检查是否黑名单模式
    private fun isBlacklistMode(): Boolean {
        return SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS) == "0"
    }

}